package com.shujia.wyh.day14.udpdemo2;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/*
    UDP协议接收端的代码编写：
        1:建立udp的socket服务.
        2:创建接收包
        3:通过receive方法接收数据
        4:将收到的数据存储到数据包对象中
        5:通过数据包对象的功能来完成对接收到数据进行解析.
        6:可以对资源进行关闭

 */
public class ReceiveDemo1 {
    public static void main(String[] args) throws Exception {
        //创建接收端的Socket对象
        DatagramSocket datagramSocket = new DatagramSocket(10086);

        while (true){
            //创建用于接收数据的包
            //public DatagramPacket(byte buf[], int length)
            byte[] bytes = new byte[1024];
            int length = bytes.length;
            DatagramPacket datagramPacket = new DatagramPacket(bytes, length);

            //3:通过receive方法接收数据
            datagramSocket.receive(datagramPacket);

            //5:通过数据包对象的功能来完成对接收到数据进行解析.
            byte[] data = datagramPacket.getData();
            String info = new String(data, 0, datagramPacket.getLength());
            InetAddress address = datagramPacket.getAddress();
            String hostName = address.getHostName();
            System.out.println("用户：" + address + hostName + "发来一条消息：" + info);
        }


//        //关闭资源
//        datagramSocket.close();
    }
}
